<template>
  <div class="my-exams">
    <div class="header">
      <h2>我的考试</h2>
      <div class="filters ka-toolbar" style="padding:8px;">
        <input v-model="keyword" placeholder="搜索考试/课程" @keyup.enter="load" />
        <select v-model="status" @change="load">
          <option value="">全部</option>
          <option value="PUBLISHED">已发布</option>
        </select>
        <el-button type="primary" @click="load">搜索</el-button>
      </div>
    </div>

    <el-empty v-if="items.length === 0 && !loading" description="暂无考试" />

    <div class="ka-grid" v-loading="loading">
      <div class="ka-card" v-for="row in items" :key="row.id" style="cursor:pointer;" @click="goTake(row.id)">
        <div class="thumb"></div>
        <div class="content">
          <span class="ka-badge">{{ row.courseName }}</span>
          <h3 style="margin:8px 0 6px;">{{ row.title }}</h3>
          <p class="text-muted" style="margin:0 0 8px;">{{ row.status === 'PUBLISHED' ? '已发布' : row.status }}</p>
          <div style="display:flex; justify-content:space-between; align-items:center;">
            <small class="text-muted">总分 {{ row.totalPoints }} · {{ row.timeLimit ? `${row.timeLimit} 分钟` : '不限时' }}</small>
            <el-button size="small" type="primary">开始/继续</el-button>
          </div>
        </div>
      </div>
    </div>

    <div class="pager">
      <el-pagination
        v-model:current-page="page"
        v-model:page-size="pageSize"
        :total="total"
        layout="total, prev, pager, next"
        @current-change="load"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { examApi } from '@/api/exam'
import { enrollmentApi } from '@/api/course'
import { getErrorMessage } from '@/api/http'

const loading = ref(false)
const items = ref<any[]>([])
const allItems = ref<any[]>([])
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
const keyword = ref('')
const status = ref('PUBLISHED')

const paginate = () => {
  const start = (page.value - 1) * pageSize.value
  const end = start + pageSize.value
  items.value = allItems.value.slice(start, end)
}

const load = async () => {
  try {
    loading.value = true
    // 学生视角：取我的选课 -> 拉每门课程的已发布考试 -> 聚合
    const enrollRes = await enrollmentApi.getMyEnrollments(1, 200)
    const courses = enrollRes.content || enrollRes.items || []
    const examLists = await Promise.all(
      courses.map(async (c: any) => {
        try {
          const resp: any = await examApi.getByCourse(c.id)
          let list: any[] = []
          if (Array.isArray(resp)) list = resp
          else if (resp?.data?.content) list = resp.data.content
          else if (resp?.content) list = resp.content
          else if (resp?.data) list = Array.isArray(resp.data) ? resp.data : [resp.data]
          return list.map((e: any) => ({ ...e, courseName: c.title }))
        } catch {
          return []
        }
      })
    )
    const merged = ([] as any[]).concat(...examLists)
      .filter((e) => (status.value ? e.status === status.value : true))
      .filter((e) => (keyword.value ? (e.title || '').includes(keyword.value) || (e.courseName || '').includes(keyword.value) : true))
    allItems.value = merged
    total.value = merged.length
    paginate()
  } catch (e: any) {
    console.error(e)
    ElMessage.error(getErrorMessage(e))
  } finally {
    loading.value = false
  }
}

const goTake = (id: number) => {
  window.location.href = `/exam/${id}`
}

onMounted(load)

watch([page, pageSize], paginate)
</script>

<style scoped>
.my-exams { padding: 20px; }
.header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px; }
.filters { display: flex; gap: 12px; width: 100%; max-width: 720px; }
.title { font-weight: 600; }
.sub { color: #909399; font-size: 12px; }
.pager { margin-top: 16px; text-align: center; }
</style>


